<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="72px"
			class="queryForms">
			<el-form-item label="返修单号" prop="repairNumber">
				<el-input v-model="queryParams.repairNumber" placeholder="请输入返修单号" clearable
					@keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="产品名称" prop="productName">
				<el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable
					@keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="产品型号" prop="productModel">
				<el-input v-model="queryParams.productModel" placeholder="请输入产品型号" clearable
					@keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="产品编号" prop="productNumber">
				<el-input v-model="queryParams.productNumber" placeholder="请输入产品编号" clearable
					@keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="计划状态" prop="planFlag">
				<el-select v-model="queryParams.planFlag" placeholder="请选择">
					<el-option label="未制定" value="0"> </el-option>
					<el-option label="已制定" value="1"> </el-option>
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>
		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" size="mini" @click="handlePlan"
					v-hasPermi="['Repair:Repair:plan']">生产计划</el-button>
			</el-col>
			<CreateForm :ids="ids" :rows="rows" formtype="t_repair" />
			<right-toolbar @changeTableData="changeTableData" menuNames="repair26" :showSearch.sync="showSearch"
				@queryTable="handleQuery" :columns.sync="columns" perm="plan:repair:index"></right-toolbar>
		</el-row>

		<div :class="sidebar.opened && eleTabTop <= 85 ? 'eleTab' : !sidebar.opened && eleTabTop <= 85 ? 'eleTabs' : ''"
			class="informationTab" ref="eleTab">
			<el-table :key="treetablekey" @expand-change="handleExpandChange" :row-class-name="row_class_name"
				@mousedown.native="mousedownTable" @row-click="row_click" @cell-mouse-enter="cell_mouse_enter"
				@cell-mouse-leave="cell_mouse_leave" @mouseup.native="mouseupTable" @mouseleave.native="mouseupTable"
				ref="table" v-loading="loading" :data="RepairList" @selection-change="handleSelectionChange"
				row-key="id" lazy :load="loadListDes" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
				border height="100%">
				<el-table-column type="selection" width="55" align="center" />
				<el-table-column label="序号" align="center" type="index" width="55">
					<template slot-scope="scope">
						<div>{{ scope.row.sort }}</div>
					</template>
				</el-table-column>
				<el-table-column label="返修任务单" prop="repairNumber" min-width="250" :show-overflow-tooltip="true"
					v-if="columns[0].visible" />
				<el-table-column label="客户代表" prop="productRepresentativeName" min-width="150"
					:show-overflow-tooltip="true" v-if="columns[1].visible" />
				<el-table-column label="用户" prop="clientName" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[2].visible" />
				<el-table-column label="产品接收时间" align="center" prop="receptionTime" min-width="150"
					:show-overflow-tooltip="true" v-if="columns[3].visible" />
				<el-table-column label="计划状态" prop="planFlagText" min-width="120" align="center"
					:show-overflow-tooltip="true" v-if="columns[11].visible">
					<template slot-scope="scope">
						<el-tag type="success" v-if="scope.row.planFlagText == '已制定'">{{ scope.row.planFlagText
						}}</el-tag>
						<el-tag type="warning" v-if="scope.row.planFlagText == '未制定'">{{ scope.row.planFlagText
						}}</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="产品名称" prop="productName" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[7].visible" />
				<el-table-column label="产品型号" prop="productModel" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[8].visible" />
				<el-table-column label="产品编号" prop="productNumber" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[9].visible" />
				<el-table-column label="3B" prop="bNumber" min-width="150" :show-overflow-tooltip="true"
					v-if="columns[10].visible" />
				<el-table-column label="故障原因" prop="failureMode" min-width="250" :show-overflow-tooltip="true"
					v-if="columns[4].visible" />
				<el-table-column label="合同号" prop="contractNumber" min-width="200" :show-overflow-tooltip="true"
					v-if="columns[5].visible" />
				<el-table-column label="监管协议号/凭证" prop="protocolNumber" min-width="200" :show-overflow-tooltip="true"
					v-if="columns[6].visible" />

				<el-table-column label="操作" class-name="small-padding fixed-width" width="200px" fixed="right"
					align="center">
					<template slot-scope="scope">
						<section v-if="scope.row.hasChildren">
							<el-button size="mini" type="text" icon="el-icon-wallet" @click="handleAnnex(scope.row)"
								v-hasPermi="['Repair:Repair:annex']">附件</el-button>
							<el-button size="mini" type="text" icon="el-icon-edit" @click="handleDetail(scope.row)"
								v-hasPermi="['Repair:Repair:detail']">详情</el-button>
						</section>
						<section v-else>
							<!-- <el-button size="mini" type="text" icon="el-icon-s-operation" @click="handlePlan(scope.row)" v-hasPermi="['Repair:Repair:plan']">生产计划</el-button> -->
							<el-button size="mini" type="text" icon="el-icon-wallet" @click="handleAnnex2(scope.row)"
								v-hasPermi="['Repair:Repair:annex2']">附件</el-button>
						</section>
					</template>
				</el-table-column>
			</el-table>
		</div>

		<pagination menuNames="Pagination30" v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
			:limit.sync="queryParams.pageSize" @pagination="getList" />

		<!-- 生产计划框 -->
		<el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body v-dialogDrag>
			<ProductPlan ref="productplan" :openApprove="open" :form="form" :productModelList="productModelList"
				:productTechnologyList="productTechnologyList" />
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>

		<!-- 返修任务详情 -->
		<el-dialog title="返修任务详情" :visible.sync="openDetail" width="900px" append-to-body v-dialogDrag>
			<RepairInfo ref="repairdetail" />
		</el-dialog>
	</div>
</template>

<script>
import { listRepair, listRepairChild, addRepair, getProductPlan, getRepair } from "@/api/plan/repair"
import ProductPlan from "./ProductPlan"
import RepairInfo from "@/views/components/RepairInfo"
import CreateForm from "@/views/components/CreateForm"
import DocumentShow from "@/views/components/DocumentShow"
import { getbind, menulist, OperationVideoMenuList } from "@/api/fileVedio/fileVedios"
import { mapGetters } from "vuex"
import { getcolumn } from "@/api/selectList"
import searchStateMixin from '@/layout/mixin/searchStateMixin.js'
export default {
	name: "RepairPlans",
	dicts: ["plan_state"],
	mixins: [searchStateMixin],
	components: { ProductPlan, RepairInfo, CreateForm, DocumentShow },
	computed: {
		...mapGetters(["sidebar"])
	},
	data() {
		return {
			tableTreeRefreshTool: {}, // 用于存储 resolve 方法和展开状态
			isMousedownTable: false, //是否按下表格
			currentEnterRow: null, //当前移入的行数据
			fileVedioList: [],
			showfileListDialog: false,
			showTodoListDialog: false,
			eleTabTop: 0, //表格容器距浏览器顶部距离
			testval: undefined,
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			// 选中数组列表
			rows: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 生产计划表格数据
			RepairList: [],
			// 弹出层标题
			title: "",
			// 是否显示弹出层
			open: false,
			// 查询参数
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				repairNumber: undefined,
				planFlag: undefined,
				productName: undefined,
				productModel: undefined,
				productNumber: undefined
			},
			// 表单参数
			form: {},
			// 表单校验
			rules: {
				// scheduleName: [{ required: true, message: "请输入计划名称", trigger: "blur" }],
			},
			deviceList: [],
			// 修改保养计划弹框
			changeOpen: false,
			changeTitle: "",
			changeForm: {},
			ruleMonths: [],
			changeDisabled: false,
			// 更新树刷新
			treeMap: new Map(),
			// isOne: true, // 是否是单条制定计划
			// 返修任务详情
			openDetail: false,
			// 制定计划产品型号列表
			productModelList: [],
			productTechnologyList: [],
			treetablekey: Math.random(),
			// 列信息
			columns: [
				{ key: 0, label: `返修任务单`, visible: true },
				{ key: 1, label: `客户代表`, visible: true },
				{ key: 2, label: `用户`, visible: true },
				{ key: 3, label: `产品接收时间`, visible: true },
				{ key: 4, label: `故障原因`, visible: true },
				{ key: 5, label: `合同号`, visible: true },
				{ key: 6, label: `监管协议号/凭证`, visible: true },
				{ key: 7, label: `产品名称`, visible: true },
				{ key: 8, label: `产品型号`, visible: true },
				{ key: 9, label: `产品编号`, visible: true },
				{ key: 10, label: `3B`, visible: true },
				{ key: 11, label: `计划状态`, visible: true }
			]
		}
	},
	created() {
		// this.getSize()
		// 如果是页面刷新，重置查询
		if (window.performance && performance.navigation.type === performance.navigation.TYPE_RELOAD) {
			// 清除URL中的查询参数（不刷新页面）
			this.resetForm("queryForm")
			window.history.replaceState({}, document.title, window.location.pathname)
		}
	},
	watch: {
		"$route.query": {
			handler(newQuery, oldQuery) {
				if (newQuery.queryData) {
					if (Object.keys(newQuery.queryData).length === 0) {
						this.resetQuerys()
						// this.getSize()
					} else {
						this.queryParams = { ...this.queryParams, ...JSON.parse(newQuery.queryData) }
						// this.getSize()
					}
				}
				this.getSize()
			},
			immediate: true, // 立即执行一次
			deep: true // 深度监听
		}
	},
	mounted() {
		// 滚动条的获取
		this.handleScrollx()
		window.addEventListener("scroll", this.handleScrollx, true)
	},
	activated() {
		// this.getSize()
		//获取表格容器距页面头部的距离
		this.handleScrollx()
	},
	destroyed() {
		window.removeEventListener("scroll", this.handleScrollx, true)
	},
	methods: {
		getSize() {
			getcolumn({ pageName: "Pagination30" }).then(response => {
				this.queryParams.pageSize = response.data.length ? (response.data[0].limit ? response.data[0].limit : 10) : 10
				this.getList()
			})
		},
		//获取表格容器距页面头部的距离
		handleScrollx() {
			this.eleTabTop = this.$refs.eleTab.getBoundingClientRect().top
		},
		/** 查询生产计划列表 */
		getList() {
			this.loading = true
			listRepair(this.queryParams).then(response => {
				this.RepairList = response.rows
				this.RepairList.forEach((item, index) => {
					item.hasChildren = true
					item.sort = index + 1
					// this.$refs.table.toggleRowExpansion(item, false)
				})
				this.total = response.total
				this.loading = false
			})
		},
		refreshLoadTree(parentId) {
			const { tree, treeNode, resolve } = this.treeMap.get(parentId)
			this.loadListDes(tree, treeNode, resolve) // 重新加载子级数据
		},
		// 关闭所有展开的行
		closeAllExpansions() {
			this.RepairList.forEach(row => {
				this.$refs.table.toggleRowExpansion(row, false)
			})
			this.getList()
		},
		// 展开/收起时触发
		handleExpandChange(row, expanded) {
			const curr = this.tableTreeRefreshTool[row.id]
			if (!curr) return
			curr.expandCount++
			if (expanded && curr.expandCount > 1 && !curr.prevStatus) {
				listRepairChild({
					id: row.id,
					...this.queryParams
				}).then(res => {
					res.rows.forEach((item, index) => {
						// 父子id会冲突
						item.id = "c" + item.id
						item.sort = index + 1
					})
					curr.resolve(res.rows)
				})
			}
			curr.prevStatus = expanded
		},
		// 获取列表子菜单
		async loadListDes(tree, treeNode, resolve) {
			if (!this.treeMap.has(tree.id)) {
				this.treeMap.set(tree.id, { tree: tree, treeNode, resolve })
			}
			this.tableTreeRefreshTool[tree.id] = {
				resolve,
				expandCount: 0, // 展开次数
				prevStatus: false // 上一次的展开状态
			}
			let queryParams = JSON.parse(JSON.stringify(this.queryParams))
			delete queryParams.pageSize
			delete queryParams.pageNum
			let data = {
				id: tree.id,
				...queryParams
			}
			let ret = await listRepairChild(data)
			ret.rows.forEach((item, index) => {
				// 父子id会冲突
				item.id = "c" + item.id
				item.sort = index + 1
			})
			resolve(ret.rows)
		},
		// 取消按钮
		cancel() {
			this.open = false
			this.$refs.table.clearSelection()
			this.reset()
		},
		// 表单重置
		reset() {
			this.form = {
				id: undefined,
				repairNumber: undefined,
				repairProductIds: undefined,
				tproductionPlanAddVoList: undefined
			}

			this.resetForm("form")
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1
			this.saveSearchState()
			this.closeAllExpansions()
			this.treetablekey = Math.random()
		},
		resetQuerys() {
			this.queryParams = {
				pageNum: 1,
				pageSize: this.queryParams.pageSize,
				repairNumber: undefined,
				planFlag: undefined,
				productName: undefined,
				productModel: undefined,
				productNumber: undefined
			},
				this.resetForm("queryForm")
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.queryParams = {
				pageNum: 1,
				pageSize: this.queryParams.pageSize,
				repairNumber: undefined,
				planFlag: undefined,
				productName: undefined,
				productModel: undefined,
				productNumber: undefined
			},
				this.resetForm("queryForm")
			this.clearSearchCache()
			this.handleQuery()
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map(item => item.id)
			this.rows = selection
			this.single = selection.length !== 1
			this.multiple = !selection.length
		},
		// 表格按下
		mousedownTable(event) {
			const target = event.target
			// 判断target的class属性确定是否点击在复选框上
			if (target.classList.contains("el-checkbox__inner")) {
				this.currentEnterRow && this.$refs.table.toggleRowSelection(this.currentEnterRow)
				this.isMousedownTable = true
			}
		},
		// 单击表格行
		row_click(row, column, event) {
			if (column && column.label == "操作") {
				return
			} else {
				this.$refs.table.toggleRowSelection(row)
			}
		},
		changeTableData() {
			this.$nextTick(() => {
				this.$refs.table.doLayout()
			})
		},

		// 进入单元格
		cell_mouse_enter(row, column, cell, event) {
			this.isMousedownTable && this.$refs.table.toggleRowSelection(row)
			this.currentEnterRow = row
		},
		// 离开单元格
		cell_mouse_leave(row, column, cell, event) {
			this.currentEnterRow = null
		},
		// 鼠标弹起或者离开表格
		mouseupTable(d) {
			this.isMousedownTable = false
		},
		// 表格每行样式
		row_class_name({ row, rowIndex }) {
			return this.rows.find(v => v.id == row.id) ? "selected" : ""
		},

		/** 生产计划操作 */
		async handlePlan() {
			this.reset()
			let data = {
				tproductionPlanPaVoList: []
			}
			if (this.ids.length == 0) {
				this.$modal.msg("请选择产品")
				return false
			} else {
				// 判断是否选中了父级返修任务
				let checkp = this.rows.find(item => {
					return Number(item.id) > 0
				})
				if (checkp) {
					this.$modal.msg("只能选择子类产品")
					return false
				}
				//生产计划只有未制定的可以点击生成计划
				let stop = false
				for (let i = 0; i < this.rows.length; i++) {
					if (this.rows[i].planFlag !== "0" && this.rows[i].planFlagText !== "未制定") {
						stop = true
						break
					}
				}
				if (stop) {
					this.$modal.msg("生产计划只有未制定的可以生成计划")
					return
				}
				let ids = []
				this.rows.forEach(e => {
					let id = e.id.replace("c", "")
					data.tproductionPlanPaVoList.push({
						id: id,
						productModel: e.productModel,
						productName: e.productName,
						productNumber: e.productNumber,
						repairId: e.repairId
					})
					ids.push(id)
				})
				this.form.repairProductIds = ids
				this.form.productNumber = ids.length
			}
			let ret = await getProductPlan(data)
			this.form.repairNumber = ret.data.repairNumber
			// 处理数据
			// 型号对象
			let productList = {}
			ret.data.productModelList.forEach(item => {
				// item.completionDays = 60 // 默认60天
				productList[item.productModel] = item
			})
			this.productModelList = productList
			// map后端不会返回空数组
			let list = ret.data.tproductTechnologyListMap
			ret.data.productModelList.forEach(item => {
				list[item.productModel] = list[item.productModel] || []
			})
			this.productTechnologyList = list
			this.open = true
			this.title = "制定生产计划"
		},

		/** 修改按钮操作 */
		handleUpdate(row) {
			this.reset()
			const id = row.id || this.ids
			getRepair(id).then(response => {
				this.form = response.data
				this.open = true
				this.title = "修改生产计划"
			})
		},
		/** 提交按钮 */
		submitForm() {
			let list = []
			for (let key in this.productModelList) {
				list.push({
					completionDays: this.form.completionDays,
					productModel: this.productModelList[key].productModel,
					tproductTechnologyList: this.productTechnologyList[key]
				})
			}
			this.form.tproductionPlanAddVoList = list
			const loading = this.$loading({
				lock: true,
				text: "Loading",
				spinner: "el-icon-loading",
				background: "rgba(0, 0, 0, 0.7)"
			})
			addRepair(this.form)
				.then(response => {
					this.$modal.msgSuccess("操作成功")
					this.open = false
					loading.close()
					this.$refs.table.clearSelection()
					localStorage.setItem("todoMessage", "planRepair1")
					this.closeAllExpansions()
					this.getList()
				})
				.finally(() => {
					loading.close()
				})
		},
		// 详情
		handleDetail(row) {
			this.title = "查看详情"
			this.openDetail = true
			this.$nextTick(() => {
				this.$refs.repairdetail.resetFormData(row.id)
			})
		},
		// 返修任务附件
		handleAnnex(row) {
			this.$router.push({
				path: "/attachment/attachmentUpload",
				query: {
					TableId: row.id,
					typeId: 6,
					perm: "Repair:Repair:annex",
					// queryParams: JSON.stringify(this.queryParams),
					paths: "/plan/repair",
				}
			})
		},
		// 产品附件
		handleAnnex2(row) {
			let id = row.id.replace("c", "")
			this.$router.push({
				path: "/attachment/attachmentUpload",
				query: {
					TableId: id,
					typeId: 7,
					perm: "Repair:Repair:annex2",
					// queryParams: JSON.stringify(this.queryParams),
					paths: "/plan/repair",
				}
			})
		},
		/** 导出按钮操作 */
		handleExport() {
			this.download(
				"/TMaintenanceSchedule/TMaintenanceSchedule/export",
				{
					...this.queryParams
				},
				`Repair_${new Date().getTime()}.xlsx`
			)
		}
	}
}
</script>

<style lang="scss" scoped></style>
